package com.kkb.mybatis.framework.sqlsource;

import com.kkb.mybatis.framework.config.BoundSql;
import com.kkb.mybatis.framework.config.DynamicContext;
import com.kkb.mybatis.framework.sqlnode.SqlNode;
import com.kkb.mybatis.framework.parser.SqlSourceParser;

/**
 *  封装了带有${}和动态标签的sql信息
 */
public class DynamicSqlSource implements SqlSource {

    private SqlNode mixedSqlNode;

    public DynamicSqlSource(SqlNode mixedSqlNode) {
        this.mixedSqlNode = mixedSqlNode;
    }

    @Override
    public BoundSql getBoundSql(Object param) {
        // 1.处理所有的sql节点，获取合并之后的完整的sql语句
        DynamicContext dynamicContext = new DynamicContext(param);
        mixedSqlNode.apply(dynamicContext);
        String sqlText = dynamicContext.getSql();

        SqlSourceParser sqlSourceParser = new SqlSourceParser();
        SqlSource sqlSource = sqlSourceParser.parse(sqlText);

        return sqlSource.getBoundSql(param);
    }
}
